
package module3;

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class SAXErrorHandling extends DefaultHandler{

    public static void main(String[] args) {
//        if(args.length  != 1){
//            //System.out.println("Usage: java SAXErrorHandling XMLDocument");
//            System.out.println("0 co doi so");
//            System.exit(1);
//        }

        SAXErrorHandling saxObject = new SAXErrorHandling();

        SAXParserFactory spfactory = SAXParserFactory.newInstance();

        try{
            SAXParser saxParse = spfactory.newSAXParser();
            //saxParse.parse(new File(args[0]), saxObject);
            saxParse.parse(new File("tomcat-users.xml"), saxObject);
        }catch(SAXParseException SPException){
            System.out.println("\n** Error occurred while parsing ** "+  ", line" + SPException.getLineNumber());
            System.out.println("  " + SPException.getMessage());
        }

        catch(SAXException sExcept){
            Exception Except = sExcept;
            if(sExcept.getException() != null){
                Except = sExcept.getException();
            }
            Except.printStackTrace();
        }

        catch(ParserConfigurationException pcExcept){
            pcExcept.printStackTrace();
        }

        catch(IOException ioExcept){
            ioExcept.printStackTrace();
        }

        catch(Throwable t){
            t.printStackTrace();
        }
        System.exit(0);
    }

    public void endDocument()throws SAXException{
        System.out.println("No error found during parsing");
    }

//    @Override
//    public void error(SAXParseException e) throws SAXException {
//        throw e;
//    }


    public void error(SAXParseException SPException) throws SAXParseException{
        throw SPException;
    }
}
